package com.zzyl.nursing.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.core.util.ObjUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.huaweicloud.sdk.iotda.v5.IoTDAClient;
import com.huaweicloud.sdk.iotda.v5.model.*;
import com.zzyl.common.constant.CacheConstants;
import com.zzyl.common.core.domain.BaseEntity;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.nursing.domain.Device;
import com.zzyl.nursing.dto.DeviceDto;
import com.zzyl.nursing.mapper.DeviceMapper;
import com.zzyl.nursing.service.IDeviceService;
import com.zzyl.nursing.vo.DeviceDetailVo;
import com.zzyl.nursing.vo.DeviceReportDataVo;
import com.zzyl.nursing.vo.ProductVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZoneOffset;
import java.util.*;

/**
 * 设备表Service业务层处理
 * 
 * @author zbr
 * @date 2025-03-05
 */
@Service
public class DeviceServiceImpl extends ServiceImpl<DeviceMapper, Device> implements IDeviceService
{
    @Autowired
    private DeviceMapper deviceMapper;

    @Autowired
    private IoTDAClient client;

    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    /**
     * 查询设备表
     * 
     * @param id 设备表主键
     * @return 设备表
     */
    @Override
    public Device selectDeviceById(Long id)
    {
        return deviceMapper.selectById(id);
    }

    /**
     * 查询设备表列表
     * 
     * @param device 设备表
     * @return 设备表
     */
    @Override
    public List<Device> selectDeviceList(Device device)
    {
        return deviceMapper.selectDeviceList(device);
    }

    /**
     * 新增设备表
     * 
     * @param device 设备表
     * @return 结果
     */
    @Override
    public int insertDevice(Device device)
    {
        return deviceMapper.insert(device);
    }

    /**
     * 修改设备表
     * 
     * @param device 设备表
     * @return 结果
     */
    @Override
    public int updateDevice(Device device)
    {
        return deviceMapper.updateById(device);
    }

    /**
     * 批量删除设备表
     * 
     * @param ids 需要删除的设备表主键
     * @return 结果
     */
    @Override
    public int deleteDeviceByIds(Long[] ids)
    {
        return deviceMapper.deleteBatchIds(Arrays.asList(ids));
    }

    /**
     * 删除设备表信息
     * 
     * @param id 设备表主键
     * @return 结果
     */
    @Override
    public int deleteDeviceById(Long id)
    {
        return deviceMapper.deleteById(id);
    }

    /**
     * 物联网平台同步产品列表
     */
    @Override
    public void syncProductList() {
        // 1.查询产品列表
        ListProductsRequest request = new ListProductsRequest();
        request.setLimit(20);
        ListProductsResponse response = client.listProducts(request);
        if (!ObjUtil.equal(response.getHttpStatusCode(), 200)) {
            throw new BaseException("物联网接口 - 查询产品，同步失败");
        }
        // 2.存储到redis
        redisTemplate.opsForValue().set(CacheConstants.IOT_ALL_PRODUCT_LIST, JSONUtil.toJsonStr(response.getProducts()));
    }

    /**
     * 查询IOT产品列表
     * @return
     */
    @Override
    public List<ProductVo> getAllProduct() {
        String json = redisTemplate.opsForValue().get(CacheConstants.IOT_ALL_PRODUCT_LIST);
        if (StrUtil.isEmpty(json)) {
            return Collections.emptyList();
        }
        return JSONUtil.toList(json, ProductVo.class);
    }

    /**
     * 注册设备
     */
    @Override
    public void register(DeviceDto dto) {
        // 1.设备名称是否重复
        Long count = lambdaQuery().eq(Device::getDeviceName, dto.getDeviceName()).count();
        if (count > 0) {
            throw new BaseException("设备名称重复");
        }
        // 2.设备标识是否重复
        count = lambdaQuery().eq(Device::getNodeId, dto.getNodeId()).count();
        if (count > 0) {
            throw new BaseException("设备标识重复");
        }
        // 3.同一位置是否绑定了相同产品
        count = lambdaQuery()
                .eq(Device::getBindingLocation, dto.getBindingLocation())
                .eq(Device::getProductKey, dto.getProductKey())
                .eq(Device::getLocationType, dto.getLocationType())
                .eq(Device::getPhysicalLocationType, dto.getPhysicalLocationType())
                .count();
        if (count > 0) {
            throw new BaseException("该老人或位置已经绑定该产品，不能重复绑定");
        }
        String secret = RandomUtil.randomString(32);
        // 4.注册设备
        AddDeviceRequest request = new AddDeviceRequest();
        AddDevice body = new AddDevice();
        AuthInfo authInfo = new AuthInfo();
        authInfo.withSecret(secret);
        body.withAuthInfo(authInfo);
        body.withDeviceName(dto.getDeviceName());
        body.withProductId(dto.getProductKey());
        body.withNodeId(dto.getNodeId());
        body.withDescription(dto.getRemark());
        request.withBody(body);
        AddDeviceResponse response = null;
        try {
            response = client.addDevice(request);
            if (response.getHttpStatusCode() != 201) {
                throw new BaseException("注册失败");
            }
        } catch (Exception e) {
            throw new BaseException("注册失败",e.getMessage());
        }
        // 5.保存到数据库
        String deviceId = response.getDeviceId();
        Device device = BeanUtil.toBean(dto, Device.class);
        device.setSecret(secret);
        device.setIotId(deviceId);
        if (!save(device)) {
            // 删除设备
            delDevice(deviceId);
            throw new BaseException("注册失败");
        }

    }

    /**
     * 根据iotId查询设备信息
     *
     * @param iotId
     * @return
     */
    @Override
    public DeviceDetailVo getByIotId(String iotId) {
        // 1.从数据库查询信息
        Device device = lambdaQuery().eq(StrUtil.isNotBlank(iotId), Device::getIotId, iotId).one();
        if (ObjectUtil.isNull(device)) {
            throw new BaseException("设备不存在");
        }
        // 2.从iot查询信息
        ShowDeviceRequest request = new ShowDeviceRequest();
        request.withDeviceId(iotId);
        ShowDeviceResponse response = client.showDevice(request);
        if (response.getHttpStatusCode() != 200) {
            throw new BaseException("查询iot设备信息失败");
        }
        String status = response.getStatus();
        String activeTimeStr = response.getActiveTime();
        // 3.合并
        DeviceDetailVo vo = BeanUtil.toBean(device, DeviceDetailVo.class);
        if (StrUtil.isNotBlank(activeTimeStr)) {
            LocalDateTime activeTime = LocalDateTimeUtil.parse(activeTimeStr, DatePattern.UTC_MS_PATTERN);
            activeTime = activeTime.atZone(ZoneId.from(ZoneOffset.UTC))
                    .withZoneSameInstant(ZoneId.of("Asia/Shanghai"))
                    .toLocalDateTime();
            vo.setActiveTime(activeTime);
        }
        vo.setDeviceStatus(status);

        return vo;
    }

    /**
     * 根据iotId删除设备
     *
     * @param iotId iotId
     */
    @Override
    public void deleteByIotId(String iotId) {
        if (!remove(new LambdaQueryWrapper<Device>().eq(StrUtil.isNotBlank(iotId),Device::getIotId, iotId))) {
            throw new BaseException("删除失败");
        }
        delDevice(iotId);
    }

    /**
     * 查询设备上报数据
     *
     * @param iotId
     * @return
     */
    @Override
    public List<DeviceReportDataVo> queryServiceProperties(String iotId) {
        // 查询上报到iot的设备数据
        ShowDeviceShadowRequest request = new ShowDeviceShadowRequest();
        request.withDeviceId(iotId);
        ShowDeviceShadowResponse response = null;
        try {
            response = client.showDeviceShadow(request);
            if (response.getHttpStatusCode() != 200) {
                throw new BaseException("查询设备数据失败");
            }
        } catch (BaseException e) {
            throw new BaseException("查询设备数据失败", e.getMessage());
        }

        List<DeviceShadowData> shadow = response.getShadow();
        if (CollUtil.isEmpty(shadow)) {
            return new ArrayList<>();
        }
        DeviceShadowData shadowData = shadow.get(0);
        String eventTimeStr = shadowData.getReported().getEventTime();
        Object properties = shadowData.getReported().getProperties();

        // 封装成vo
        ArrayList<DeviceReportDataVo> list = new ArrayList<>();
        if (properties instanceof Map) {
            Map<String, Object> map = (Map<String, Object>) properties;
            map.forEach((key, value) -> {
                LocalDateTime eventTime = LocalDateTimeUtil.parse(eventTimeStr, "yyyyMMdd'T'HHmmss'Z'");
                eventTime = eventTime.atZone(ZoneId.from(ZoneOffset.UTC))
                        .withZoneSameInstant(ZoneId.of("Asia/Shanghai"))
                        .toLocalDateTime();
                list.add(new DeviceReportDataVo(key, eventTime, Integer.parseInt(value.toString())));
            });
        }
        return list;
    }

    /**
     * 修改设备信息
     *
     * @param device
     */
    @Override
    public void updateDeviceById(Device device) {
        Device deviceForIot = lambdaQuery()
                .eq(Device::getId, device.getId())
                .one();
        Device deviceUsed = lambdaQuery()
                .eq(Device::getId, device.getId())
                .select(Device::getId,
                        Device::getDeviceName,
                        Device::getBindingLocation,
                        Device::getLocationType,
                        Device::getNodeId,
                        Device::getPhysicalLocationType,
                        Device::getProductKey,
                        Device::getDeviceName,
                        BaseEntity::getRemark,Device::getDeviceDescription)
                .one();
        // 判断是否修改
        if (ObjUtil.equal(device,deviceUsed)) {
            throw new BaseException("设备信息未修改");
        }
        // 判断设备类型是否修改
        if (!ObjUtil.equal(device.getLocationType(),deviceUsed.getLocationType())) {
            throw new BaseException("设备类型不允许修改");
        }
        // 判断设备名称修改后是否重复
        Device deviceSearchByUpdateName = lambdaQuery().eq(Device::getDeviceName, device.getDeviceName()).one();
        if (ObjUtil.isNotNull(deviceSearchByUpdateName) && !ObjUtil.equal(deviceSearchByUpdateName.getId(),device.getId())) {
            throw new BaseException("设备名称已存在");
        }
        // 判断位置是否重复
        Device deviceSearchByLocation = lambdaQuery()
                .eq(Device::getBindingLocation, device.getBindingLocation())
                .eq(Device::getProductKey, device.getProductKey())
                .eq(Device::getLocationType, device.getLocationType())
                .eq(Device::getPhysicalLocationType, device.getPhysicalLocationType())
                .one();
        if (ObjUtil.isNotNull(deviceSearchByLocation) && !ObjUtil.equal(deviceSearchByLocation.getId(),device.getId())) {
            throw new BaseException("该老人或位置已经绑定该产品，不能重复绑定");
        }
        // 修改iot设备信息
        String iotId = deviceForIot.getIotId();
        UpdateDeviceRequest request = new UpdateDeviceRequest();
        request.withDeviceId(iotId);
        UpdateDevice body = new UpdateDevice();
        body.withDeviceName(device.getDeviceName());
        body.withDescription(device.getRemark());
        request.withBody(body);
        UpdateDeviceResponse response = null;
        try {
            response = client.updateDevice(request);
            if (response.getHttpStatusCode() != 200) {
                throw new BaseException("修改设备信息失败");
            }
        } catch (BaseException e) {
            throw new BaseException("修改设备信息失败",e.getMessage());
        }

        // 修改数据库信息
        if (!updateById(device)) {
            throw new BaseException("修改失败");
        }
    }

    /**
     * 查询产品详情
     *
     * @param productKey
     * @return
     */
    @Override
    public List<ServiceCapability> queryProduct(String productKey) {
        ShowProductRequest request = new ShowProductRequest();
        request.withProductId(productKey);
        try {
            ShowProductResponse response = client.showProduct(request);
            List<ServiceCapability> serviceCapabilitiesList = response.getServiceCapabilities();
            if (CollUtil.isEmpty(serviceCapabilitiesList)) {
                return new ArrayList<>();
            }
            return serviceCapabilitiesList;
        } catch (Exception e) {
            throw new BaseException("查询产品服务模型失败");
        }
    }

    /**
     * 删除设备
     * @param deviceId
     */
    private void delDevice(String deviceId) {
        DeleteDeviceRequest requestDel = new DeleteDeviceRequest();
        requestDel.withDeviceId(deviceId);
        try {
            client.deleteDevice(requestDel);
        } catch (Exception e) {
            throw new BaseException("删除失败",e.getMessage());
        }
    }

}
